﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JXT.PrimaryKey.Batman.Reflection;
using JXT.PrimaryKey.Batman.Validation;
using JXT.PrimaryKey.Batman.Domain.Models;
using Microsoft.Practices.Unity.InterceptionExtension;

namespace JXT.PrimaryKey.Batman.Domain.Validation
{
    public class ValidationAttribute : ICallHandler
    {
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            for (int i = 0; i < input.Arguments.Count; i++)
            {
                if (input.Arguments[i] is IEntity)
                {
                    var result = validateParameter(input.Target, input.Arguments[i]);
                    if (!result.IsValid)
                        throw new ValidationException("entity validate error.", result.Errors);
                }
            }
            var retvalue = getNext()(input, getNext);
            return retvalue;
        }

        private ValidationResult validateParameter(object target, object parameter)
        {
            object obj = target.GetType().GetMetadataCacheItem("Validator").Property.Get(target);
            return (ValidationResult)obj.GetType().GetMethod("Validate").GetLambdaMethodInfo().Invoke(obj, parameter);
        }

        public int Order { get; set; }
    }
}
